package service

import (
	"goBasic/zhangxiaokun/bean"
	"goBasic/zhangxiaokun/dao"
)

type TransaService struct {
	TransaDao *dao.TransaDao
	UserDao *dao.UserDao

}

func (service *TransaService) Init(UserDao *dao.UserDao, TransaDao *dao.TransaDao) {
	service.TransaDao = TransaDao
	service.UserDao = UserDao
}

/**
转账交易
 */
func (service *TransaService) TransferAccounts(transa *bean.Transa) (hashId int) {
	userDao := service.UserDao
	transaDao := service.TransaDao

	//查询用户

	fromUser := userDao.GetUser(transa.FromUserId)
	toUser := userDao.GetUser(transa.ToUserId)

	//转账
	isSuccess := fromUser.SubBalance(transa.Amount)
	if isSuccess {
		toUser.AddBalance(transa.Amount)
	}


	//更新 库数据
	userDao.UpdateUser(fromUser)
	userDao.UpdateUser(toUser)
	hashId = transaDao.SaveTransa(transa)

	return hashId
}


func (transaService *TransaService) GetTransaByHashId(hashId int) *bean.Transa {
	return transaService.TransaDao.GetTransa(hashId)
}

/**
获取所有交易记录
 */
func (transaService *TransaService) GetAllTransa () []*bean.Transa {
	return transaService.TransaDao.GetAllTransa()
}